import Request from '@/js_sdk/luch-request/luch-request/index.js'
import { removeTicket } from '@/utils/auth.js'
import store from '../store/index.js'
import context from '../main.js'
let dialogFlag = false
const getTokenStorage = () => {
	let ticket = ''
	try {
		ticket = uni.getStorageSync('ticket')
	} catch (e) {}
	// ticket = '04a59859d5de097d23270d403fc0ec9e-5-1632651400533';
	console.log(ticket);
	return ticket
}

const http = new Request()
http.setConfig((config) => {
	config.sslVerify = false; // 验证 ssl 证书 仅5+App安卓端支持（HBuilderX 2.3.3+）
	return config
})


http.interceptors.request.use((config) => {
	/* 请求之前拦截器。可以使用async await 做异步操作 */
	let platformId = '1ec8b3dcf312488ead30f26e736d024e';
	if (getApp().globalData.channel === 'xm') {
		platformId = '0389b7d8a13e488489cb2644820db1a7';
	} else if (getApp().globalData.channel === 'xybaby') {
		platformId = '3e5e19e3bd844dda8196d4f57a1d58d0';
	}
	console.log(platformId)
	const url = config.url;
	console.log(url)
	if (url.indexOf('/wx/api/portal/login') === -1) {
		config.header = {
			...config.header,
			ticket: getTokenStorage(),
			platformId
		}
	} else {
		config.header = {
			...config.header,
			platformId
		}
	}

	/*
 if (!token) { // 如果token不存在，return Promise.reject(config) 会取消本次请求
   return Promise.reject(config)
 }
 */
	return config
}, (config) => {
	return Promise.reject(config)
})

http.interceptors.response.use(async (response) => {
	/* 请求之后拦截器。可以使用async await 做异步操作  */
	// console.log(response)
	const res = response.data
	if(process.env.NODE_ENV == 'development'){
		console.log(response);
	}
	if (res.code !== '000000') {
		if (res.code === '000001' || res.code === '000011') {
			if (!dialogFlag) {
				dialogFlag = true
				uni.showModal({
					title: '登录超时，请重新登录!',
					showCancel: false,
					success() {
						dialogFlag = false
						removeTicket();
						uni.reLaunch({
							url: '/pages/login',
						})
					}
				})
			}
			return;
		}
		const config = response.config;
		const url = config.url;
		if (url.indexOf('wx/api/portal/login?redirect=') === -1) {
			context.$u.toast(res.msg);
		}
		return Promise.reject(res)
	} else {
		return res
	}
}, (response) => { // 请求错误做点什么。可以使用async await 做异步操作
	console.log(response)
	return Promise.reject(response)
})

export {
	http,
}
